package com.icodingedu.springcloud.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.icodingedu.springcloud.entity.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class JwtService {

    //生产环境中应该从外部加密后获取
    private static final String KEY = "you must change it";
    //生产环境中应该从外部加密后获取
    private static final String ISSUER = "icodingedu";
    //定义个过期时间
    private static final long TOKEN_EXP_TIME = 60000;
    //定义一个传入的参数名
    private static final String USERNAME = "username";

    /**
     * 生成token
     * @param account
     * @return
     */
    public String token(Account account){
        //生成token的时间
        Date now = new Date();
        Algorithm algorithm = Algorithm.HMAC256(KEY);

        String token = JWT.create()
                .withIssuer(ISSUER) //解密的时候如果不知道发行方也无法解密
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXP_TIME)) //过期时间
                .withClaim(USERNAME,account.getUsername())
//                .withClaim(ROLE,account.getRole())
                .sign(algorithm);
        log.info("jwt generated user={}",account.getUsername());
        return token;
    }

    /**
     * 验证token
     * @param token
     * @param username
     * @return
     */
    public boolean verify(String token,String username){
        log.info("verify jwt - user={}",username);
        try{
            //解密要和加密算法一致
            Algorithm algorithm = Algorithm.HMAC256(KEY);
            //构建一个验证器
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .withClaim(USERNAME,username)
                    .build();
            verifier.verify(token);
            return true;
        }catch (Exception ex){
            log.error("auth failed",ex);
            return false;
        }
    }
}
